import React, {Component} from 'react';
import {
    Image,
    StyleSheet,
    Text,
    View,
    TextInput,
    TouchableOpacity,
    StatusBar,
} from 'react-native';
import Main from "../third"
import Util from '../../util/MD5Util'
import ASUtil, {param} from '../../util/AsyncStorgeUtil';
import ScrollableTabView, {DefaultTabBar} from "react-native-scrollable-tab-view";

import ChooseProvince from './chooseProvince';
import MyNavigator from "../../comps/normal/myNavigator";
import NetUtil from '../../util/NetWorkUtil';
import UrlUtils from "../../util/UrlCollection";
/**
 * 登录界面
 */
export default class LoginAndRegisterPage extends Component {

    render() {
        console.log(this.props.log);
        console.log(this.props.schoolName);
        console.log(this.props.schoolId);
        var rootRoute = {
            component: LoginPage,
            passProps:{
                log:this.props.log,
                schoolId:this.props.schoolId,
                schoolName:this.props.schoolName
            }
        };
        return (
            <MyNavigator rootRoute={rootRoute}/>
        );

    }
}

class LoginPage extends Component {
    constructor() {
        super();
        this.state = {
            /************************************
             * 登录相关
             ************************************/
            name: "", //登录用户名
            pass: "", //登录密码
            /************************************
             * 注册相关
             ************************************/
            reg_name: '', //注册姓名
            reg_mail: '', //注册手机号/邮箱
            reg_pass: '', //注册密码
            reg_confirm: '', //注册确认密码
            reg_school: '', //注册选择学校
            reg_role: '', //注册身份

            log: 1, //标记 1为登录界面, 2为注册界面
        }
    }

    render() {
        if (this.state.log === 1&&this.props.log==null) {
            //登录组件
            return (
                <LoginCom th={this}/>
            );
        } else {
            //注册组件
            return (
                <RegisterCom th={this}/>
            );
        }
    }
}

//登录组件
class LoginCom extends Component{
    render(){
        let th=this.props.th;
        return(
            <View style={styles.container}>
                <StatusBar hidden={false} backgroundColor='#0e8586'/>
                <Image source={require("../../img/logo.png")} style={styles.welcome}></Image>

                <TextInput style={[styles.input, {marginBottom: 15}]}
                           placeholder="请输入手机号或账号"
                           ref="tv_account"
                           onChangeText={(text) => {
                               th.setState(() => {
                                   th.state.name = text;
                               })
                           }}
                >
                </TextInput>
                <TextInput style={styles.input} placeholder='请输入密码'
                           ref="tv_account"
                           onChangeText={(text) => {
                               th.setState(() => {
                                   th.state.pass = text;
                               })
                           }}
                >
                </TextInput>
                <TouchableOpacity activeOpacity={0.9} style={styles.touchable} onPress={() => {
                    if (th.state.name == "" & th.state.pass == "") {
                    } else {
                        login(th);
                    }
                }}>
                    <Text style={styles.instructions}>登录
                    </Text>
                </TouchableOpacity>

                <Text style={styles.text_login}
                      onPress={() => {
                          th.setState({
                              log: 2
                          })
                      }}
                >没有MOORs账号?点击注册</Text>
            </View>
        );
    }
}

//注册组件
class RegisterCom extends Component{
    render(){
        let th=this.props.th;
        return(
            <View style={{flex: 1, backgroundColor: '#F5FCFF'}}>
                <StatusBar hidden={false} backgroundColor='#0e8586'/>

                <View style={{flex: 2, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF'}}>
                    <Image source={require("../../img/logo.png")} style={styles.welcome_register}></Image>
                </View>

                <ScrollableTabView
                    style={{
                    flex: 0.8,
                    backgroundColor: '#F5FCFF',
                    marginTop: 20,
                    marginLeft: 20,
                    marginRight: 20,
                    justifyContent: 'center'
                }}
                    onChangeTab={(obj) => {
                        console.log('indexNumber:' + (obj.i+1));
                        this.setState({
                            reg_role: obj.i
                        })
                    }}
                    renderTabBar={() => <DefaultTabBar/>}
                    locked={true}
                    tabBarActiveTextColor='#36ADAB'
                    tabBarInactiveTextColor='#000'
                    // tabBarUnderlineStyle={{backgroundColor: '#36ADAB'}}
                    tabBarUnderlineStyle={{backgroundColor: '#36ADAB', width: 81, marginLeft: 42, height: 2}}
                    // tabBarWithoutAnimation={false}
                    tabBarTextStyle={{fontSize: 14}}
                >

                    <Text tabLabel="我是学生" style={{height: 10}}></Text>
                    <Text tabLabel="我是教师" style={{height: 10}}></Text>
                </ScrollableTabView>

                <View style={[styles.container_register, {flex: 6}]}>
                    <TextInput style={[styles.input_register, {marginTop: 5}]}
                               ref="tv_reg_name"
                               underlayColor={'#444'}
                               placeholder="你的姓名"
                               onChangeText={(text) => {
                                   th.setState(() => {
                                       th.state.reg_name = text;
                                   })
                               }}
                    >
                    </TextInput>
                    <TextInput style={styles.input_register} placeholder='手机号/邮箱'
                               ref="tv_reg_mail"
                               onChangeText={(text) => {
                                   th.setState(() => {
                                       th.state.reg_mail = text;
                                   })
                               }}
                    >
                    </TextInput>
                    <TextInput style={styles.input_register} placeholder='设置密码'
                               ref="tv_reg_pass"
                               onChangeText={(text) => {
                                   th.setState(() => {
                                       th.state.reg_pass = text;
                                   })
                               }}
                    >
                    </TextInput>
                    <TextInput style={styles.input_register} placeholder='确认密码'
                               ref="tv_reg_confirm"
                               onChangeText={(text) => {
                                   th.setState(() => {
                                       th.state.reg_confirm = text;
                                   })
                               }}
                    >
                    </TextInput>
                    <TextInput style={[styles.input_register]} placeholder='选择学校'
                               ref="tv_reg_school"
                               value={th.props.schoolName}
                               onFocus={()=>{
                                   var nextRoute = {
                                       component: ChooseProvince,
                                   };
                                   th.props.navigator.push(nextRoute);
                               }}
                    >
                    </TextInput>

                    <TouchableOpacity activeOpacity={0.9} style={[styles.touchable, {marginBottom: 0}]}
                                      onPress={() => {
                                          if (_regIsValied(this,th)) {
                                              _register(th);
                                          }
                                      }}>
                        <Text style={styles.instructions}>注册</Text>
                    </TouchableOpacity>

                    <Text style={[styles.text_login, {bottom: -62}]}
                          onPress={() => {
                              th.setState({
                                  log: 1
                              })
                          }}
                    >已有MOORs账号?点击登录</Text>
                </View>
            </View>
        );
    }
}


function login(th) {
    let url = UrlUtils.login;
    let databody = 'username=' + th.state.name + '&password=' + Util.getMD5(th.state.pass);

    NetUtil.postForm(url,databody,
        (responseJson)=>{
            var data = responseJson;
            console.debug("DEBUG:  " + JSON.stringify(data));
            gotoThird(responseJson, th);
            return responseJson;
        },
        (error)=>{
            console.error("error:  " + error);
        })
}

/**
 * 验证是否登陆成功,成功则挑转界面
 * @param responseJson 请求返回值
 * @param th 上下文对象
 */
function gotoThird(responseJson, th) {
    if (responseJson.result == true) {
        ASUtil.setParam(param.userId, responseJson.user.id);
        ASUtil.setParam(param.username, responseJson.user.username);
        ASUtil.setParam(param.userRole, responseJson.user.authorities[0]);

        var nextRoute = {
            component: Main,
            passProps:{
                name:responseJson.user.username,
            }
        };
        th.props.navigator.push(nextRoute);
    } else {
        alert(responseJson.result);
    }
}

function getError(err) {
    if (err) {
        alert(err)
    }
}

/**
 * 验证注册表单是否填写完整
 * @param th1 局部上下文
 * @param th2 全局上下文
 * @private
 */
function _regIsValied(th1,th2) {
    let tv_name = th1.refs.tv_reg_name;
    let tv_mail = th1.refs.tv_reg_mail;
    let tv_pass = th1.refs.tv_reg_pass;
    let tv_confirm = th1.refs.tv_reg_confirm;
    let tv_school = th1.refs.tv_reg_school;

    console.log("name: "+th2.state.reg_name);
    console.log("mail: "+th2.state.reg_mail);
    console.log("pass: "+th2.state.reg_pass);
    console.log("confirm: "+th2.state.reg_confirm);
    console.log("school: "+th2.state.schoolName);

    if (th2.state.reg_name == null || th2.state.reg_name == '') {
        tv_name.setNativeProps({
            underlineColorAndroid: '#900'
        });
        return false;
    }
    if (th2.state.reg_mail == null || th2.state.reg_mail == '') {
        tv_mail.setNativeProps({
            underlineColorAndroid: '#900'
        });
        return false;
    }if (th2.state.reg_pass == null || th2.state.reg_pass == '') {
        tv_pass.setNativeProps({
            underlineColorAndroid: '#900'
        });
        return false;
    }if (th2.state.reg_confirm == null || th2.state.reg_confirm == '') {
        tv_confirm.setNativeProps({
            underlineColorAndroid: '#900'
        });
        return false;
    }if (th2.props.schoolName == null || th2.props.schoolName == '') {
        tv_school.setNativeProps({
            underlineColorAndroid: '#900'
        });
        return false;
    }
    return true;
}

/**
 * 注册操作
 */
function _register(th){
    // role:学生为1, 教师为2
    let url = "https://edu.bjzjmy.com:4455/register/users";
    // let databody = 'username=' + th.state.name + '&password=' + Util.getMD5(th.state.pass);
    let databody = 'userName=' + th.state.reg_name + '&userId=' + th.state.reg_mail
                    +'&password='+th.state.reg_pass+ '&confirmPassword='+th.state.reg_confirm
                    +'&schoolId='+th.props.schoolId+'&registerFrom=PHONE'
                    +'&cassflx='+th.state.reg_role;
    let opts = {
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: databody,
    };
    this.fetch(url, opts)
        .then((response) => response.json())
        .then((responseJson) => {
            var data = responseJson;
            console.debug("DEBUG:  " + JSON.stringify(data));
            return responseJson;
        })
        .catch((error) => {
            if (error)
                console.error("error:  " + error);
        });
}

const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
        welcome: {
            marginBottom: 55,
            width: 150,
            height: 40,
            resizeMode: Image.resizeMode.stretch
        },
        instructions: {
            marginTop: 14,
            fontSize: 17,
            alignItems: 'center',
            textAlign: 'center',
            color: '#F5FCFF',
        },
        input: {
            marginBottom: 20,
            height: 50,
            width: 320,
        },
        touchable: {
            marginBottom: 175,
            marginTop: 20,
            alignItems: 'center',
            height: 50,
            width: 320,
            backgroundColor: '#00B0AD'
        },
        text_login: {
            fontSize: 12,
            color: '#00B0AD',
            bottom: -55,
        },
        welcome_register: {
            // marginBottom: 110,
            flex: 3,
            marginTop: 50,
            width: 150,
            height: 40,
            resizeMode: Image.resizeMode.center
        },
        container_register: {
            flex: 1,
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
        input_register: {
            height: 50,
            width: 320,
        }
    });